package com.ist.neartweat;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.net.Socket;

import com.ist.neartweat.messages.Message;
import com.ist.neartweat.messages.RegistrationMessage;

public class ClientHandlerThread extends Thread{
	NearTweatServer server ;
	Socket clientSocket ;
	Boolean isRegistered=false;
	String ClientId;
	public ClientHandlerThread(NearTweatServer server, Socket clientSocket){
		this.server = server;
		this.clientSocket = clientSocket;

	}

	public void run(){
		Boolean loop = true;
		ObjectInputStream ois =null;
		ObjectOutputStream ops = null;
		try {
			ops = new ObjectOutputStream(clientSocket.getOutputStream());
			ops.flush();
			ois = new ObjectInputStream(clientSocket.getInputStream());

		} catch (IOException e1) {

			e1.printStackTrace();
		}

		while(loop){
			try {
				Message msg = (Message)ois.readObject();
				if(msg instanceof RegistrationMessage){
					this.ClientId= ((RegistrationMessage) msg).getClientId();
					System.out.println("Received Registration Request Message from client "+((RegistrationMessage) msg).getClientId());
					Boolean status = server.addClient(((RegistrationMessage) msg).getClientId(),clientSocket);
					if(status = true){
						isRegistered = true;
					}
				}
				else{
					if(isRegistered == true){
						server.handleMessage(msg);
					}

					else{
						//Send Register First Message to the client. Or this client has hacked the system.
						//Can be implemented later.
					}

				}

			} catch (StreamCorruptedException e) {
				System.out.println("Exception in ClientHandlerThread of Client = "+this.ClientId);
				loop =false;
				e.printStackTrace();
			} catch (IOException e) {
				loop =false;
				System.out.println("Exception in ClientHandlerThread of Client = "+this.ClientId);
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				loop =false;
				System.out.println("Exception in ClientHandlerThread of Client = "+this.ClientId);
				e.printStackTrace();
			}
		}
	}
}
